﻿using Lightworks.Core.Cache;
using Microsoft.AspNetCore.Authorization;

namespace Lightworks.Core.Auth
{
    public class PermissionAuthHandler : AuthorizationHandler<AuthAttribute>
    {
        ICacheService cache;
        public PermissionAuthHandler(ICacheService cache) 
        {
            this.cache = cache;
        }
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, AuthAttribute requirement)
        {            
            if (!context.User.Identity.IsAuthenticated) //没认证直接退回
            {
                return Task.CompletedTask;
            }
            if (string.IsNullOrEmpty(requirement.PermCode)
                || context.User.Identity.Name == "admin") // 没有标注权限表示，默认为认证即可访问,管理员直接放行
            {
                context.Succeed(requirement);
            }
            HashSet<string> permissions = cache.Get<HashSet<string>>($"system:user:perms:{context.User.Identity.Name}");
            if(permissions ==null || permissions.Count ==0) 
            {
                return Task.CompletedTask;
            }
            if (permissions.Contains(requirement.PermCode)) 
            {
                context.Succeed(requirement);
            }
            return Task.CompletedTask;
        }
    }
}
